/*!
 * 语音上传模块
 * @author Sherlock 
 * ----------------------------
 * uploaded 上传完成 但未保存属性的函数
 * dosave 保存后的回调函数
 */

require( '../imageUploader/style.less' );
define( [ 'require', 'jquery', 'message', 'qiniu', 'constants', 'selector', 'api' ], function( require, $, ShowTitleMessage ) {
  var returnParam = {};

  var showTime = ShowTitleMessage.showTime;
  var constants = require( 'constants' );
  var apis = require( 'api' ).FILEUPLOAD;
  var me = returnParam.$selector = $( '#sound_upload' );
  var soundQiniuUpload = new QiniuJsSDK();

  $( '.video_classify ', me ).selectpicker( {
    size: 5
  } );

  var option_sound = {
    runtimes: 'html5,flash,html4', // 上传模式,依次退化
    browse_button: 'sound_upload_qiniu', // 上传选择的点选按钮，**必需**
    uptoken_url: apis.GET_VOICE_UPTOKEN, // Ajax 请求 uptoken 的 Url，**强烈建议设置**（服务端提供）
    get_new_uptoken: false, // 设置上传文件的时候是否每次都重新获取新的 uptoken
    domain: constants.qiniuDomainVideo, // bucket 域名，下载资源时用到，**必需**
    max_file_size: '2mb', // 最大文件体积限制
    flash_swf_url: 'path/of/plupload/Moxie.swf', //引入 flash,相对路径
    max_retries: 0, // 上传失败最大重试次数
    dragdrop: true, // 开启可拖曳上传
    chunk_size: '2mb', // 分块上传时，每块的体积
    auto_start: true, // 选择文件后自动上传，若关闭需要自己绑定事件触发上传,
    multi_selection: 0,
    filters: {
      mime_types: [ {
        title: "Voice files",
        extensions: "mp3,wma,wmv,amr"
      } ]
    },
    init: {
      'FileUploaded': function( up, file, info ) {

        ShowTitleMessage.show( "语音上传成功", showTime );
        // $(".image_upload").parent().find('.add_icon1').attr('style','display:none');
        // $(".image_upload").text('重新上传');
        $( '.btn_upload_video', me ).text( '重新上传' );
        var content = '<audio id="example_sound_qiniu" controls sound_id="' + $.parseJSON( info ).voice_id + '" sound_name="' + jQuery.parseJSON( info ).voice_name + '">' +
          '<source src="' + $.parseJSON( info ).address + '"  />' +
          '</audio>';
        $( '.video_preview', me ).html( content );

        if ( $.isFunction( returnParam.uploaded ) ) {
          returnParam.uploaded.call( this, up, file, info );
        }

        $( '.progress_bar', me ).fadeOut();
      },
      'Error': function( up, err, errTip ) {
        if ( err.code === -600 ) {
          ShowTitleMessage.showWarning( '文件大小超出限制', showTime );
        } else if ( err.code === -601 ) {
          ShowTitleMessage.showWarning( '格式仅支持mp3、wma、wmv、amr', showTime );
        } else {
          ShowTitleMessage.showWarning( '上传出现问题，请重试', showTime );
        }
        $( '.progress_bar', me ).hide().css( {
          'width': '0%'
        } );
        $( 'input[type="file"]', me ).val( '' );
      },
      'Key': function( up, file ) {
        var name = file.name;
        var ext = name.split( "." );
        var key = constants.userLogin + '_' + ( new Date().getTime() ) + parseInt( Math.random() * 100 ) + '.' + ext[ 1 ];
        return key;
      },
      'BeforeUpload': function( up, file ) {
        $( '.progress_bar', me ).fadeIn().find( '.bar' ).width( 0 );
      },
      'UploadProgress': function( up, file ) {
        $( '.progress_bar .bar', me ).css( {
          'width': file.percent + '%'
        } );
      }
    }
  };
  soundQiniuUpload.uploader( option_sound );

  function multipleParam( option ) {
    var param = {
      maxOptions: 5,
      selectedTextFormat: "values",
      multipleSeparator: ',',
      noneSelectedText: '请选择',
      size: 8
    }
    if ( option ) {
      return $.extend( param, option );
    } else {
      return param;
    }
  }
  /*
   * 文本长度监听
   */
  $( ".txt_right_bor_null", me ).bind( "input propertychange", function() {
    var area = $( this ).val().length;
    $( ".spa_fontcount > span", me ).text( area );
  } );

  $( '#buttonUpload', me ).click( function() {
    var is_show = 0;
    var sound_id = $( '#example_sound_qiniu', me ).attr( 'sound_id' );
    //var address1 = $('#example_sound_qiniu', me).attr('sound_address');
    var address = $( '#example_sound_qiniu>source', me ).prop( 'src' );

    if ( !address ) {
      ShowTitleMessage.showWarning( "请先上传语音", showTime );
      return;
    }
    var title = $( '.txt_right_bor_null', me ).val();
    if ( !title ) {
      ShowTitleMessage.showWarning( "请输入语音标题", showTime );
      return;
    }

    var classify = $( 'select.video_classify', me ).val();

    if ( classify == '未分类' ) {
      ShowTitleMessage.showWarning( "请先选择分类", showTime );
      return;
    }
    //语音标签判断
    // var label = '';
    // $( '.tag-choosed-video', me ).find( 'button' ).each( function() {
    // 	label += $( this ).text() + ',';
    // } )
    // label = label.substring( 0, label.length - 1 );
    // if ( !label ) {
    // 	ShowTitleMessage.showWarning( "请输入标签", showTime );
    // 	return;
    // }
    //var custom = $('#classify', me).val();
    if ( $( '#video_share', me ).is( ':checked' ) ) {
      is_show = 1;
    }
    var paramData = {
      voice_id: sound_id,
      title: title,
      classify: classify,
      //label: label,
      //address1: address1,
      address: address,
      //custom: custom,
      is_show: is_show
    }

    ShowTitleMessage.show( "正在保存" );

    function timeToStr( time ) {
      var h = 0,
        m = 0,
        s = 0,
        _h = '00',
        _m = '00',
        _s = '00';
      time = parseInt( time );
      h = Math.floor( time / 3600 );
      time = Math.floor( time % 3600 );
      m = Math.floor( time / 60 );
      s = Math.floor( time % 60 );
      _s = s < 10 ? '0' + s : s + '';
      _m = m < 10 ? '0' + m : m + '';
      _h = h < 10 ? '0' + h : h + '';
      return _m + ":" + _s;
    }
    var _duration = $( '#example_sound_qiniu', me )[ 0 ].duration;
    var soundData = $.extend( paramData, {
      length: timeToStr( _duration )
    } );
    $.post( apis.SAVE_VOICE, paramData, function( data ) {
      ShowTitleMessage.show( "语音保存成功", showTime );
      var htm = $.parseJSON( data );
      $( '#fm_sound_upload', me.modal( 'hide' ) )[ 0 ].reset();

      if ( $.isFunction( returnParam.doSave ) ) {
        returnParam.doSave.call( this, htm, soundData );
      }
    } );
  } );

  // -----------------------------上传语音标签处理-------------------------
  $( '.select-tag-video', me ).selectpicker( multipleParam() ).change( function() {
    var valList = $( this ).val() + "";
    var array = valList.split( ',' );
    var html = '';
    if ( array ) {
      for ( var i = 0; i < array.length; i++ ) {
        html += '<button type="button">' + array[ i ] + '</button>';
      }
    }
    $( '.tag-choosed-video>.system-tag', me ).html( html );
  } );
  $( '.tag-choosed-video>.system-tag', me ).on( 'click', 'button', function() {
    $( this ).remove();
    var tagArray = new Array();
    $( '.tag-choosed-video>.system-tag>button', me ).each( function() {
      tagArray.push( $( this ).text() );
    } );
    $( '.select-tag-video' ).selectpicker( 'val', tagArray );
  } );
  $( '.tag-choosed-video>.custom-tag', me ).on( 'click', 'button', function() {
    $( this ).remove();
    $( '.select-tag-video', me ).selectpicker( multipleParam( {
      maxOptions: ( 5 - $( '.tag-choosed-video button', me ).length + $( '.tag-choosed-video>.system-tag>button', me ).length )
    } ) );
  } );
  // 手动加标签
  $( '#inp-addtag-sound', me ).keyup( function( e ) {
    e = e || event;
    var regx = /,/;
    var strRep = $.trim( $( this ).val() ).replace( /\s+/g, '' );
    var lastStr = strRep.substr( strRep.length - 1 );
    if ( regx.test( lastStr ) || e.keyCode == 13 ) {
      var tagLen = $( '.tag-choosed-video button', me ).length;
      var flag = true;
      $( '.tag-choosed-video button', me ).each( function() {
        if ( strRep == $( this ).text() ) {
          ShowTitleMessage.showWarning( '已存在相同的标签', showTime );
          flag = false;
          return false;
        }
      } );
      if ( tagLen < 5 ) {
        if ( $( '.tag-choosed-video>.custom-tag>button', me ).length == 4 && $( '.tag-choosed-video>.system-tag>button', me ).length == 0 ) {
          ShowTitleMessage.showWarning( '请至少选择一个系统标签', showTime );
          $( this ).val( '' );
          return;
        }
        if ( !flag ) {
          $( this ).val( '' );
          return;
        }
        var html = '';
        var array = strRep.split( ',' );
        for ( var i = 0; i < array.length; i++ ) {
          if ( array[ i ] != '' ) {
            html += '<button type="button">' + array[ i ] + '</button>';
          }
        }
        if ( html != '' ) {
          $( '.tag-choosed-video>.custom-tag', me ).append( html );
          $( '.select-tag-video', me ).selectpicker( multipleParam( {
            maxOptions: ( 5 - tagLen - 1 + $( '.tag-choosed-video>.system-tag>button' ).length )
          } ) );
        } else {
          ShowTitleMessage.showWarning( '空白标签无法添加', showTime );
        }
        $( this ).val( '' );
      } else {
        $( this ).val( '' );
        ShowTitleMessage.showWarning( '系统和自定义标签总共最多五个', showTime );
      }
    }
  } );

  $( '#fm_sound_upload', me ).on( 'reset', function() {

    $( '.select-tag-video', this ).selectpicker( 'val', [] );
    $( '.video_classify', this ).selectpicker( 'val', '未选择' );
    $( '.selectpicker', this ).selectpicker( 'refresh' );
    $( '.system-tag, .custom-tag, .video_preview', this ).empty();
    $( '#sound_upload_qiniu', this ).text( '上传语音' );
    $( '.spa_fontcount>span', this ).text( 0 );
  } );


  return returnParam;

} );
